package cn.zhage.aimin.canal.client.handler;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import org.springframework.core.ResolvableType;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
 * 
 * @author 渣哥
*/
public interface RowDataHandler <T>{
    <T> void handle(CanalEntry.RowData rowData, CanalEntry.EventType eventType, EntityHandler<T> entityHandler);

    default <T> T buildEntity(EntityHandler<T> entityHandler, List<CanalEntry.Column> columns){
        ResolvableType resolvableType = ResolvableType.forClass(entityHandler.getClass());
        ResolvableType anInterface = resolvableType.getInterfaces()[0];
        Class<?> resolve = anInterface.getGeneric(0).resolve();

        Map<String, Object> hashMap = new HashMap<>();
        for(CanalEntry.Column column: columns){
            hashMap.put(column.getName(), column.getValue());
        }
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return (T)objectMapper.convertValue(hashMap, resolve);
    }
}
